import { connect } from 'react-redux'
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { Component } from 'react'
import map from '@/utils/map'
import { CrossDomain } from '@/utils/cross-domain'
import { nearStore, storeInfo } from '@/api'
import { updateStore, initLocation, setOpenLocation } from '@/store/location/action'
// 引入 WebView 组件
import { WebView, View } from '@tarojs/components'
import { carInfo } from '@/store/car/action'
import onNavigation from '@/utils/command/onNavigation'

const domain: string = `${BASE_H5_URL}/#`
type State = {
  webUrl: string,
  currentCar: any
}
type paramsData = {
  carId: string
  accessId: string
  accessKey: string
  storeCode: String
  serverTime: number,
	distributionLeaderId:any,
	userId:string,
	mobile:[number,string]
}
@connect<any>(({ location, car, maintain }) => ({ location, car, maintain }), _dispatch => ({
  dispatchStore(params) {
    return _dispatch(updateStore(params))
  },
  // 缓存 当前区域经纬度，当前区域信息，城市名
  dispatchLocation(params) {
    return _dispatch(initLocation(params))
  },
  // 位置授权状态（true: 已开启，false: 未开启）
  dispatchOpenLocation(status) {
    return _dispatch(setOpenLocation(status))
  },
  dispatchCarInfo() {
    return _dispatch(carInfo())
  }
}))
export default class AppWebView extends Component<any, State> {
	$instance = getCurrentInstance()
  async handleMessage(e) {
    console.log(e)
  }

  config = {
    navigationBarTitleText: '',
    enablePullDownRefresh: true
  }

  constructor (props) {
    super(props)
    this.state = {
      webUrl: '',
      currentCar: {}
    }
  }
  async UNSAFE_componentWillMount() {
		console.log('--进来webview--')
    let { query, path, rest } =  this.$instance.router.params
		path = '/distribution/user'
    let authInfo: any = Taro.getStorageSync('IS_USERINFO')
    let distributionLeaderId: any = Taro.getStorageSync('DISTRIBUTION_LEADER_ID')
    let herf = this.setHref(path, query)

    // 判断是否有门店信息  有直接跳转  没有获取附近门店列表取最近
    const storeCode = Taro.getStorageSync('STORECODE')
    if (!storeCode) {
      const { dispatchOpenLocation, location, dispatchLocation } = this.props
      //获取位置信息
      let curLocation: any = await map.getLocation(true)
      const { isOpenLocation } = location
      if (curLocation) {
        if (!isOpenLocation) {
          // 当用户开启定位授权，更新状态
          if (curLocation) {
            await dispatchOpenLocation(true)
          } else {
            // 没有开启定位授权，如果有历史地址，则拿历史记录地址
            const storageAddress = Taro.getStorageSync('CUSTOMA_DDRESS')
            if (storageAddress) {
              dispatchLocation(storageAddress)
              return
            }
          }
        }
        await this.getNearStore(curLocation)
      }
    }
    if (!this.props.car.carInfo.currentCar) {
      Taro.showLoading({ title: '拉取车型数据中' })
      this.props.dispatchCarInfo().then(() => {
        let data: paramsData = {
          carId: this.props.car.carInfo.currentCar ? this.props.car.carInfo.currentCar.id : '',
          accessId: authInfo.accessId,
          userId: authInfo.userId,
          accessKey: authInfo.accessKey,
          storeCode: Taro.getStorageSync('STORECODE'),
          serverTime: authInfo.serverTime,
					distributionLeaderId:distributionLeaderId ? distributionLeaderId : '',
					mobile:authInfo.mobile
        }
        let url = new CrossDomain({
          url: herf,
          data: data
        }).init()
        if (rest) {
          url = `${url}&${rest}`
        }
        this.setState({
          webUrl: url
        })
        Taro.hideLoading()
      })
    } else {
      let data: paramsData = {
        carId: this.props.car.carInfo.currentCar ? this.props.car.carInfo.currentCar.id : '',
        accessId: authInfo.accessId,
        accessKey: authInfo.accessKey,
        userId: authInfo.userId,
        storeCode: Taro.getStorageSync('STORECODE'),
        serverTime: authInfo.serverTime,
				distributionLeaderId:distributionLeaderId ? distributionLeaderId : '',
				mobile:authInfo.mobile,
      }
      let url = new CrossDomain({
        url: herf,
        data: data
      }).init()
      if (rest) {
        url = `${url}&${rest}`
      }
      this.setState({
        webUrl: url,
        currentCar: this.props.car.carInfo.currentCar
      })
    }
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    // this.UNSAFE_componentWillMount()
    let currentCar = nextProps.car.carInfo.currentCar
    if (currentCar && currentCar.carLicense !== this.state.currentCar.carLicense) {
      let { query, path, rest} =  this.$instance.router.params
			path = '/distribution/user'
      let authInfo: any = Taro.getStorageSync('IS_USERINFO')
      let distributionLeaderId: any = Taro.getStorageSync('DISTRIBUTION_LEADER_ID')
			console.log('path********',path)
      let herf = this.setHref(path, query)
      let data: paramsData = {
        carId: currentCar ? currentCar.id : '',
        userId: authInfo.userId,
        accessId: authInfo.accessId,
        accessKey: authInfo.accessKey,
        storeCode: Taro.getStorageSync('STORECODE'),
        serverTime: authInfo.serverTime,
				distributionLeaderId:distributionLeaderId ? distributionLeaderId : '',
				mobile:authInfo.mobile,
      }
      let url = new CrossDomain({
        url: herf,
        data: data
      }).init()
      if (rest) {
        url = `${url}&${rest}`
      }
      this.setState({
        webUrl: '',
      }, () => {
        setTimeout(() => {
          this.setState({
            webUrl: url,
            currentCar: currentCar ? currentCar : {}
          })
        }, 10)
      })
    }
    // Taro.startPullDownRefresh()
  }


  // 获取附近门店列表
  async getNearStore(curLocation) {
    const { dispatchStore } = this.props

    let paramData = {
      userLongitude: curLocation.longitude,
      userLatitude: curLocation.latitude,
      query: {
        page: 1,
      }
    }
    let GOODS_DISTRIBUTION_ID = Taro.getStorageSync('GOODS_DISTRIBUTION_ID')
    if (GOODS_DISTRIBUTION_ID) {
      paramData.query['goodsDistributionId'] = GOODS_DISTRIBUTION_ID
      Taro.setStorageSync('GOODS_DISTRIBUTION_ID', null)
    }

    // 获取附近门店 取第一个
    await nearStore(paramData).then(async (res) => {
      const { data: { data } } = res
      if (data.length > 0) {
        await dispatchStore(data[0])
      }
    })
  }

  parseQueryString(url) {
    var params = {}
    var arr = url.split('?')
    if (arr.length <= 1)
      return params
    arr = arr[1].split('&')
    for (var i = 0, l = arr.length; i < l; i++) {
      var a = arr[i].split('=')
      params[a[0]] = a[1]
    }
    return params
  }

  getMessage(e) {
    const { dispatchStore } = this.props
    console.log('执行', e)
    if (e && e.target && e.target.data[0]) {
      let { path, query, storeCode, returnLocation } = e.target.data[0]
      // console.log('e', e)
      if (path) {
        let newQuery = this.parseQueryString(path)
				if (path.includes('?')) {
					onNavigation({ contentType: 4, serviceItems: `${path}?type=${newQuery.type ? newQuery.type:''}`})
				} else {
					onNavigation({ contentType: 4, serviceItems: `${path}?type=${newQuery.type ? newQuery.type:''}`})
				}
      }
      if (storeCode) {
        // 返回storeCode 如果不一致，则更新
        const STORECODE = Taro.getStorageSync('STORECODE')
        if (Number(STORECODE) != Number(storeCode)) {
          storeInfo(
            { storeCode }
          ).then(res => {
            dispatchStore(res.data.data)
          })
        }
      }
      // 如果有返回选择门店
      if (returnLocation) {
        Taro.setStorageSync('REDIRECT_PATH', returnLocation)
      }
    }
  }

  setHref(path, query: any) {
    path = path ? path : ''
    if (path && path.indexOf('http') !== 0) {
      path = `${domain}${path}`
    }
    console.log('query: ', query);
    return this.setUrlQuery({
      // url: `${domain}${path}`,
      url: path,
      query: query ? JSON.parse(query) : null
    })
  }

  setUrlQuery(options) {
    console.log('options', options)
    let { url, query } = options;
    if (!url) return '';
    if (query) {
      let queryArr: any = []
      for (const key in query) {
        if (query.hasOwnProperty(key)) {
          queryArr.push(`${key}=${query[key]}`)
        }
      }
      if (url.indexOf('?') !== -1) {
        url = `${url}&${queryArr.join('&')}`
      } else {
        url = `${url}?${queryArr.join('&')}`
      }
    }
    return url;
  }

  render() {
    const { webUrl } = this.state
    if (!webUrl) return null
    console.log(webUrl)
    return (
      <View>
        {webUrl ? <WebView src={`${webUrl}`} onMessage={(e) => this.getMessage(e)} /> : null}
      </View>
    )
  }
}
